var mySpace = {};

var tapaha = function(oArgs) {
	this.oArgs = oArgs || {};
	
	this._svg = null;
	this._drawMode = null;
	this._dragObject= null;
	this._objShape = null;
	this._drawNodes = [];
	this._recentNode = null;
	this._offset = null;
	this._start = null;
	this._outline = null;
	this._surface = null;
	this._pressShift = false;
	this._currX = 0;
	this._currY = 0;
	this._mouseOffset = null;
	this._points = [];
	this._polyline = null;
	this._circlePoints = [];
	
	var that = this;
	
	this.init = function() {
		jQuery('#content').svg({onLoad: function(svg) { 
			that._svg = svg; 
			that._surface = svg.rect(0, 0, '100%', '100%', {id: 'surface', fill: '#20deaa'}); 
			jQuery(that._surface).mousedown(that.startDrag).mousemove(that.dragging).mouseup(that.endDrag); 
			jQuery(that._surface).click(that.setPoints);
			//resetSize(svg, '100%', '100%');
			}
		});

		//event등록
		jQuery("#btn_move").click(function() {
			that._drawMode = "move";
		});
		jQuery("#btn_rect").click(function() {
			that._drawMode = "draw";
			that._objShape = "rect";
		});
		jQuery("#btn_circle").click(function() {
			that._drawMode = "draw";
			that._objShape = "circle";
		});
		jQuery("#btn_ellipse").click(function() {
			that._drawMode = "draw";
			that._objShape = "ellipse";
		});
		jQuery("#btn_polyline").click(function() {
			that._drawMode = "points";
			that._objShape = "polyline";
		});
		
		jQuery(document).keydown(function(ev) {
			if (event.keyCode == 16) {
				that._pressShift = true;
			}
		});
		jQuery(document).keyup(function(ev) {
			//keyCode == 16 == Shift
			if (event.keyCode == 16) {
				that._pressShift = false;
			}
		});
	};
	this._getMouseOffset = function(target, ev) {
		ev = ev || window.event;
		
		var docPos = that._getPosition(target);
		var mousePos = that._mouseCoords(ev);
		
		return {x:mousePos.x - docPos.x, y:mousePos.y - docPos.y};
	};
	this._mouseCoords = function(ev) {
		if(ev.pageX || ev.pageY) {
			return {x:ev.pageX, y:ev.pageY};
		}
		return {
			x:ev.clientX + document.body.scrollLeft - document.body.clientLeft,
			y:ev.clientY + document.body.scrollTop - document.body.clientTop
		};
	};
	this._getPosition = function(e) {
		var left = 0;
		var top = 0;
		
		while(e.offsetParent) {
			left += e.offsetLeft;
			top += e.offsetTop;
			e = e.offsetParent;
		}
		left += e.offsetLeft;
		top += e.offsetTop;
		
		return {x:left, y:top};
	};
	this.setPoints = function(ev) {
		if(that._drawMode !== "points") return;
		
		if(!that._polyline) {
			that._polyline = that._svg.polyline(that._points, {fill: 'yellow',stroke: 'red',strokeWidth: 2});
		}
		
		that._offset = (jQuery.browser.msie ? {left: 0, top: 0} : jQuery('#content').offset());
			
		if (!jQuery.browser.msie) {
			that._offset.left -= document.documentElement.scrollLeft || document.body.scrollLeft;
			that._offset.top -= document.documentElement.scrollTop || document.body.scrollTop;
		}
		var curr_point = [ev.clientX - that._offset.left, ev.clientY - that._offset.top];
		that._drawPointCircle(curr_point[0], curr_point[1]);
		that._points.push(curr_point);
		
		if(that._points.length > 2) {
			that._svg.change(that._polyline, {points: that._points});
		}
		
		console.log(that._points);
		ev.preventDefault();
	};
	this._drawPointCircle = function(x, y) {
		var r = 4;
		var circle_point = that._svg.circle(x + r/2, y + r/2, r, {strokeWidth:2,stroke:"blue",fill:"red"});
		
		that._circlePoints[that._circlePoints.length] = circle_point;
		
		jQuery(circle_point).click(function() {
			console.log("circle clicked");
			if(x == that._points[0][0] && y == that._points[0][1]) {
				that._clearCirclePoints();
			}
		});
		
		console.log(that._circlePoints);
	};
	this._clearCirclePoints = function() {
		for(var i=0; i<that._circlePoints.length; i++) {
			jQuery(that._circlePoints[i]).remove();
		}
	};
	this.startDrag = function (ev) {
		if(that._drawMode === "move") {
			if(jQuery(this).attr("id") === "surface") return;
			
			that._dragObject = this;
			that._mouseOffset = that._getMouseOffset(this, ev);
			
			console.log(that._dragObject.tagName);
			//console.log(jQuery(that._dragObject).val());
			
			if(that._dragObject.tagName == "rect") {
				that._currX = jQuery(that._dragObject).attr("x");
				that._currY = jQuery(that._dragObject).attr("y");
			} else if(that._dragObject.tagName == "circle" || that._dragObject.tagName == "ellipse") {
				that._currX = jQuery(that._dragObject).attr("cx");
				that._currY = jQuery(that._dragObject).attr("cy");
			} else if(that._dragObject.tagName == "polyline") {
				
			}
			that._mouseOffset.x -= that._currX;
			that._mouseOffset.y -= that._currY;
			
			//console.log("x :" + that._currX + " y : " + that._currY);
		} else if(that._drawMode === "draw") {
			that._offset = (jQuery.browser.msie ? {left: 0, top: 0} : jQuery('#content').offset());
			
			if (!jQuery.browser.msie) {
				that._offset.left -= document.documentElement.scrollLeft || document.body.scrollLeft;
				that._offset.top -= document.documentElement.scrollTop || document.body.scrollTop;
			}
			that._start = {X: ev.clientX - that._offset.left, Y: ev.clientY - that._offset.top};
			ev.preventDefault();
		}
	};
	this.dragging = function(ev) {
		if (that._drawMode == "move" && (that._dragObject)) {
			that._mousePos = that._mouseCoords(ev);
			//console.log("==== x :" + that._mousePos.x + " y : " + that._mousePos.y);
			
			var settings = {};
			
			if(that._dragObject.tagName == "rect") {
				settings.x = that._mousePos.x - that._mouseOffset.x;
				settings.y = that._mousePos.y - that._mouseOffset.y;
			} else if(that._dragObject.tagName == "circle" || that._dragObject.tagName == "ellipse") {
				settings.cx = that._mousePos.x - that._mouseOffset.x;
				settings.cy = that._mousePos.y - that._mouseOffset.y;
				//console.log(settings.transform);
			}
			that._svg.change(that._dragObject, settings);	
		}
		else if (that._drawMode === "draw") {
			if (!that._start) return;
			if (!that._outline) {
				that._outline = that._svg.rect(0, 0, 0, 0, {
					fill: 'none',
					stroke: 'red',
					strokeWidth: 2,
					strokeDashArray: '2,2,2'
				});
				jQuery(that._outline).mouseup(that.endDrag);
			}
			that._objSize = that.getSize(Math.abs(ev.clientX - that._offset.left - that._start.X), Math.abs(ev.clientY - that._offset.top - that._start.Y));
			
			that._svg.change(that._outline, {
				x: Math.min(ev.clientX - that._offset.left, that._start.X),
				y: Math.min(ev.clientY - that._offset.top, that._start.Y),
				width: that._objSize.w,
				height: that._objSize.h
			});
			//console.log("x : " + Math.min(ev.clientX - that._offset.left, that._start.X) + ", y : " + Math.min(ev.clientY - that._offset.top, that._start.Y) + ", width : " + that._objSize.w + ", height : " + that._objSize.h);
			ev.preventDefault();
		} else if(that._drawMode === "points") {
			if(that._points.length == 0) return;
			//console.log("dragging points");
			if (!that._outline) {
				that._outline = that._svg.line(0, 0, {
					fill: 'none',
					stroke: 'red',
					strokeWidth: 3,
					strokeDashArray: '2,2,2'
				});
				//jQuery(that._outline).mouseup(that.endDrag);
			}
			//that._objSize = that.getSize(Math.abs(ev.clientX - that._offset.left - that._start.X), Math.abs(ev.clientY - that._offset.top - that._start.Y));
			
			that._svg.change(that._outline, {
				x1: that._points[that._points.length-1][0],
				y1: that._points[that._points.length-1][1],
				x2: ev.clientX - that._offset.left,
				y2: ev.clientY - that._offset.top
			});
			//console.log(that._points[that._points.length-1][0]+ "," +that._points[that._points.length-1][1]);
			//console.log(ev.clientX - that._offset.left);
			//console.log("start : (" +that._points[that._points.length-1][0]+","+that._points[that._points.length-1][1]+") finish : ("+ev.clientX - that._offset.left+","+ev.clientY - that._offset.top+")");
			ev.preventDefault();
		}
	};
	this.endDrag = function(ev) {
		if (that._drawMode === "move" && (that._dragObject)) {
			that._dragObject = null;
		}
		else {
			if (!that._start) return;
			
			jQuery(that._outline).remove();
			that._outline = null;
			//that._drawShape(that._start.X, that._start.Y, ev.clientX - that._offset.left, ev.clientY - that._offset.top); 
			that._drawShape(that._start.X, that._start.Y, that._objSize.w + that._start.X, that._objSize.h + that._start.Y);
			that._start = null;
			that._objSize = null;
			//that._drawMode = "move"; //도형을 그린후에는 이동상태로 변경
			ev.preventDefault();
		}
	};
	this.getSize = function(width, height) {
		if(that._pressShift == true) {
			return width >= height ? {w:height, h:height} : {w:width, h:width}
		} else {
			return {w:width, h:height}
		}
	};
	this._drawShape = function(x1, y1, x2, y2) {
		var left = Math.min(x1, x2); 
	    var top = Math.min(y1, y2); 
	    var right = Math.max(x1, x2); 
	    var bottom = Math.max(y1, y2); 
	    //var settings = {fill: $('#fill').val(), stroke: $('#stroke').val(),strokeWidth: $('#swidth').val()};
		var settings = {fill: "#cbcbcb", stroke: "black",strokeWidth: 4};  
		
		switch(that._objShape) {
			case "rect" :
				that._recentNode = that._svg.rect(left, top, right - left, bottom - top, settings);
				break;
			case "ellipse" :
				//원인 경우
				if(that._pressShift == true) {
					var r = Math.min(right - left, bottom - top) / 2; 
					that._recentNode = that._svg.circle(left + r, top + r, r, settings);
				} else { //타원인 경우
					var rx = (right - left) / 2; 
       				var ry = (bottom - top) / 2; 
        			that._recentNode = that._svg.ellipse(left + rx, top + ry, rx, ry, settings); 
				}
				break;
		}
		that._drawNodes[that._drawNodes.length] = that._recentNode;
		jQuery(that._recentNode).mousedown(that.startDrag).mousemove(that.dragging).mouseup(that.endDrag);
		jQuery("#content").focus();
	};
	/*
	this._drag = function(ev) {
		if (that._drawMode == "move") {
			that._mouseOffset = that._getMouseOffset(this, ev);
			console.log("x : " + that._mouseOffset.x + " y : " + that._mouseOffset.y);
			
			var x = event.offsetX - jQuery(this).attr("x");
			var y = event.offsetY - jQuery(this).attr("y");
			
			jQuery(this).attr({x : event.offsetX + x, y : event.offsetY + y});
		}
	};
	*/
}

jQuery(function() {
	var t = new tapaha();
	t.init();
});
